package com.lovo.common.shiro;


import com.lovo.common.bean.UserInfoBean;
import com.lovo.common.dao.IUserInfoDAO;
import com.lovo.common.util.WebUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Component
public class JWTRealm extends AuthorizingRealm {
    @Resource
    private IUserInfoDAO userInfoDAO;
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

//        //获取当前登录的用户
//        UserInfoBean userInfoBean = (UserInfoBean) principalCollection.getPrimaryPrincipal();
//        //通过SimpleAuthenticationInfo做授权
//        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//        List<RoleInfoBean> roleInfoBeans = userInfoBean.getRoleInfoBeans();
//        List<FunctionInfoBean> functionInfoBeans = functionInfoService.selectByRoleIds(roleInfoBeans);
//        for (RoleInfoBean role : roleInfoBeans) {
//            //添加角色
//            simpleAuthorizationInfo.addRole(role.getRoleName());
//        }
//        for (FunctionInfoBean function : functionInfoBeans) {
//            //添加权限
//            simpleAuthorizationInfo.addStringPermission(function.getFuncName());
//        }
//        return simpleAuthorizationInfo;
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getPrincipal();
        if(token == null || "".equals(token)){
            return null;
        }
        UserInfoBean userInfoBean = null;
        try {
            userInfoBean = WebUtil.verifyToken(token,userInfoDAO);
        } catch (IOException e) {}
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userInfoBean,token,getName());
        return simpleAuthenticationInfo;
    }
}
